import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['Times New Roman']

styles = ['-', '-.', '--', ':', 'solid',
          'dashed', 'dotted', 'dashdot', 'dashed']
markers = [' ', '>', '8', '*', 'x', '+', 'p', 'D']
colors = ["red", "orange", "blue", "c", "cyan",
          "brown", "mediumvioletred", "dodgerblue", "green"]


def load_a_file_res(filename):
    """
    读取一个结果文件
    """
    with open(filename, 'r') as f:
        row_list = f.read().splitlines()
    a_day_res = row_list[0].split('|')
    
    prefix = filename.split('/')[-1][0:3]
    if '16_' == prefix:
        a_day_res = [float(i) / 68985 for i in a_day_res]
    if '17_' == prefix:
        a_day_res = [float(i) / 67999 for i in a_day_res]
    return a_day_res


def make_filename_list(prefix):
    coe_list = ['1_2', '1_5', '1_8', '2_0']
    # coe_list = ['1_2', '1_5']
    un_server_num_list = [100, 200]
    time_list = [12]
    res = []
    for t in time_list:
        for coe in coe_list:
            for num in un_server_num_list:
                res.append(f'{prefix}/16_{t}_{coe}_{num}.txt')
                res.append(f'{prefix}/17_{t}_{coe}_{num}.txt')
    return res


def load_many_files_res(filename_list):
    """
    将某方法多个结果文件汇总成一组数据
    然后得出统计量，提供画图数据
    """
    res = []
    for filename in filename_list:
        res += load_a_file_res(filename)
    return res


def draw_plot(data_dict):
    """
    Input: 接受任意数量的数据，key充当画图的图例，value是画图用的原始数据
    """
    plt.figure(figsize=(8, 4))
    # 适配曲线数量
    count = 0
    for k, data in data_dict.items():
        x = []
        size = len(data)
        for i in range(size):
            x.append(i)
        # plt.bar(x, data, #label=k,
        #          linestyle=styles[count], color=colors[count], linewidth=2.5)

        # sns.lineplot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        plt.plot(x, data, label=k, linestyle=styles[count], color=colors[count], linewidth=2.5)
        count += 1

    # plt.ylim(1000, 5000)
    # plt.xlim(0, 22)
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=20)
    plt.xlabel("Time(h)", fontsize=20)
    plt.ylabel("Error", fontsize=20)
    plt.grid()
    plt.legend()
    # plt.legend(ncol=5, loc='lower center', bbox_to_anchor=(0.6, 0), fontsize=15, framealpha=0.5,
    #     borderpad=0.1,handletextpad=0.1, handlelength=1, columnspacing=0.2)
    return plt

def draw_cdf_from_dict(data_dict):
    """绘制CDF图
    Input: 接受任意数量的数据，key充当画图的图例，value是画图用的原始数据
    """
    plt.figure(figsize=(8, 4))
    # 适配曲线数量
    count = 0
    for k, data in data_dict.items():
        x = sorted(data)
        y = []
        size = len(x)
        for i in range(size):
            # y.append(1 - i / size)
            y.append(i / size)
        plt.plot(x, y, label=k,
                 linestyle=styles[count], color=colors[count], linewidth=2.5)
        # plt.plot([2.0,3.0],[2,2],label=k,
        #          linestyle=styles[count], color=colors[count], marker=markers[count],linewidth=2.5)
        # scatter_x = []
        # scatter_y = []
        # scatter_value = [0.1, 0.01, 0.001, 0.0001]
        # for i in range(len(scatter_value)):
        #     for p_index, p in enumerate(y):
        #         if p < scatter_value[i]:
        #             scatter_x.append(x[p_index])
        #             scatter_y.append(y[p_index])
        #             break
        # if count > 0:
        #     plt.scatter(scatter_x, scatter_y,
        #                 marker=markers[count], s=100, color=colors[count])
        count += 1

    # plt.ylim(0.001, 1)
    # plt.xlim(0, 20)
    plt.yticks(fontsize=27)
    plt.xticks(fontsize=27)
    # plt.yscale("symlog", linthreshy=0.0001)
    plt.xlabel("Workload rejection rate", fontsize=27)
    plt.ylabel("CDF", fontsize=27)
    plt.grid()
    plt.legend(fontsize = 27)
    # plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower center",
    #            mode="expand", borderaxespad=0, ncol=3, frameon=False, fontsize=14)
    return plt


if __name__ == "__main__":
    # 单个文件结果
    # max_flow_overload = load_a_file_res('./max_flow_overload_fix/16_12_3_0_100.txt')
    # max_flow_best_overload = load_a_file_res('./max_flow_best_overload_fix/16_12_3_0_100.txt')


    # 汇总多个文件结果
#    max_flow_overload_filenames = make_filename_list('./max_flow_overload_fix')
#    max_flow_overload = load_many_files_res(max_flow_overload_filenames)
#
#
#    max_flow_best_overload_filenames = make_filename_list('./max_flow_best_overload_fix')
#    max_flow_best_overload = load_many_files_res(max_flow_best_overload_filenames)
#
#    linear_best_minloss_overload_filenames = make_filename_list('./linear_best_minloss_overload')
#    linear_best_minloss_overload = load_many_files_res(linear_best_minloss_overload_filenames)
#
#    linear_best_rand_overload_filenames = make_filename_list('./linear_best_rand_overload')
#    linear_best_rand_overload = load_many_files_res(linear_best_rand_overload_filenames)
#
#    linear_minloss_overload_filenames = make_filename_list('./linear_minloss_overload')
#    linear_minloss_overload = load_many_files_res(linear_minloss_overload_filenames)
#
#    linear_rand_overload_filenames = make_filename_list('./linear_rand_overload')
#    linear_rand_overload = load_many_files_res(linear_rand_overload_filenames)
    balance_filenames = make_filename_list('./overload_error/pool_real2')
    balance_overload = load_many_files_res(balance_filenames)


    rand_filenames = make_filename_list('./overload_error/real')
    rand_overload = load_many_files_res(rand_filenames)
    
    rand_best_filenames = make_filename_list('./overload_error/robust_poolround')
    rand_best_overload = load_many_files_res(rand_best_filenames)

    # robust_float_filenames = make_filename_list('./overload_error/robust_float')
    # robust_float = load_many_files_res(robust_float_filenames)

    robust_balance_pool_filenames = make_filename_list('./overload_error/robust_balance_pool')
    robust_balance_pool = load_many_files_res(robust_balance_pool_filenames)

    data_dict = {
        'RO-RP': robust_balance_pool,
        'RO-only': rand_best_overload,
        'RP-Only': balance_overload,
        'TwithLB': rand_overload,
        # 'robust_float': robust_float,
    }

    pt = draw_cdf_from_dict(data_dict)
    pt.tight_layout()
    file_name = __file__.split('/')[-1].split('.')[0]
    # pt.savefig(f"{file_name}.pdf", bbox_inches='tight')
    pt.show()
